import socket
from bencode import bencode


class Krpc(object):

    __slots__ = ("port", "types", "actions", "sock")

    def __init__(self, port):
        self.port = port
        self.types = {
            b"r": self.response_received,
            b"q": self.request_received
        }
        self.actions = {
            b"ping": self.ping_received,
            b"find_node": self.find_node_received,
            b"get_peers": self.get_peers_received,
            b"announce_peer": self.announce_peer_received,
        }
        self.sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
        self.sock.bind(("0.0.0.0", self.port))

    def response_received(self, msg, address):
        self.find_node_handler(msg)

    def request_received(self, msg, address):
        try:
            self.actions[msg["q"]](msg, address)
        except KeyError:
            pass

    def send_krpc(self, msg, address):
        try:
            self.sock.sendto(bencode(msg), address)
        except Exception:
            pass

    def announce_peer_received(self, msg, address):
        pass

    def get_peers_received(self, msg, address):
        pass

    def find_node_received(self, msg, address):
        pass

    def ping_received(self, msg, address):
        pass

    def find_node_handler(self, msg):
        pass
